/**
 * 验证数据库时区配置
 */
const db = require('./src/config/database');

async function verifyTimezone() {
  try {
    console.log('=== 检查数据库时区配置 ===\n');
    
    // 1. 检查MySQL全局时区
    const [globalTz] = await db.query('SELECT @@global.time_zone as global_tz, @@session.time_zone as session_tz');
    console.log('1. MySQL时区设置:');
    console.log('   全局时区:', globalTz[0].global_tz);
    console.log('   会话时区:', globalTz[0].session_tz);
    console.log('');
    
    // 2. 检查当前时间
    const [times] = await db.query('SELECT NOW() as mysql_now, UNIX_TIMESTAMP(NOW()) as unix_timestamp');
    console.log('2. MySQL当前时间:');
    console.log('   MySQL NOW():', times[0].mysql_now);
    console.log('   Unix时间戳:', times[0].unix_timestamp);
    console.log('   Node.js时间:', new Date());
    console.log('');
    
    // 3. 检查clients表的最新记录
    const [clients] = await db.query(`
      SELECT 
        client_id,
        hostname,
        last_heartbeat,
        NOW() as current_time,
        TIMESTAMPDIFF(SECOND, last_heartbeat, NOW()) as seconds_ago,
        UNIX_TIMESTAMP(last_heartbeat) as heartbeat_unix,
        UNIX_TIMESTAMP(NOW()) as now_unix
      FROM clients 
      ORDER BY last_heartbeat DESC 
      LIMIT 1
    `);
    
    if (clients.length > 0) {
      console.log('3. 最新客户端记录:');
      console.log('   客户端ID:', clients[0].client_id.substring(0, 30) + '...');
      console.log('   主机名:', clients[0].hostname);
      console.log('   最后心跳:', clients[0].last_heartbeat);
      console.log('   当前时间:', clients[0].current_time);
      console.log('   时间差(秒):', clients[0].seconds_ago);
      console.log('   心跳Unix时间戳:', clients[0].heartbeat_unix);
      console.log('   当前Unix时间戳:', clients[0].now_unix);
      console.log('');
      
      // 4. 计算时区差异
      const nodejsNow = Math.floor(Date.now() / 1000);
      const diff = nodejsNow - clients[0].now_unix;
      console.log('4. 时区验证:');
      console.log('   Node.js Unix时间戳:', nodejsNow);
      console.log('   MySQL Unix时间戳:', clients[0].now_unix);
      console.log('   时间差(秒):', diff);
      
      if (Math.abs(diff) < 5) {
        console.log('   ✅ 时区配置正确！');
      } else {
        console.log('   ❌ 时区配置有问题！时间相差', Math.abs(diff), '秒');
        console.log('');
        console.log('修复建议:');
        if (diff > 0) {
          console.log(`   - MySQL时间慢了 ${diff} 秒`);
          console.log('   - 检查MySQL服务器时区设置');
          console.log('   - 或在 database.js 中调整 timezone 参数');
        } else {
          console.log(`   - MySQL时间快了 ${Math.abs(diff)} 秒`);
          console.log('   - 检查系统时间是否正确');
        }
      }
    } else {
      console.log('3. ⚠️  数据库中没有客户端记录');
    }
    
    console.log('\n=== 检查完成 ===');
    process.exit(0);
  } catch (error) {
    console.error('❌ 检查失败:', error);
    process.exit(1);
  }
}

verifyTimezone();
